package com.ingenio.siot.servlet;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.JSONArray;
import org.json.JSONObject;

import com.ingenio.siot.adapter.MonitoreoAdapter;
import com.ingenio.siot.adapter.MovilAdapter;
import com.ingenio.siot.entity.Punto;

/**
 * Servlet implementation class MonitoreoMovilesServlet
 */
@WebServlet("/MonitoreoMoviles")
public class MonitoreoMovilesServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public MonitoreoMovilesServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String[] idsTipoMovil = request.getParameterValues("idsTipoMovil[]");
		
		if (idsTipoMovil != null) {
			MonitoreoAdapter ma = new MonitoreoAdapter();
			MovilAdapter mova = new MovilAdapter();
			List<Punto> puntos = ma.devolverMonitoreo(idsTipoMovil);
			try{		
				JSONObject json = new JSONObject();
				JSONArray ja = new JSONArray();
				
				for (Punto p : puntos) {
				   JSONObject jo = new JSONObject();
				   jo.put("lat", p.getLatitud());
				   jo.put("lng", p.getLongitud());
				   jo.put("fecha", p.getFecha());
				   jo.put("img", ((mova.devolverMovil(p.getId_movil())).getTipoMovil()).getUrlIcono());
				   jo.put("patente", p.getPatente());
				   jo.put("descMovil", p.getDescMovil());
				   ja.put(jo);
				}
				json.put("puntos", ja);
				response.setContentType("application/json");
				response.getWriter().write(json.toString());
			}
			catch(Exception e){
				
			}
		}
		else {
			
		}
	}
}
